package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.client.ProductFeignClient;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;


    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * 返回全部列表
     *
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<SeckillGoods> seckillGoodsList = seckillGoodsService.findAll();
        return Result.ok(seckillGoodsList);
    }

    @GetMapping("getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId) {
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        return Result.ok(seckillGoods);
    }

    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getseckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {
        //生成下单码，放入result 对象中.使用userId生成下单码。 对这个userId 进行使用md5加密就行了.
        String userId = AuthContextHolder.getUserId(request);

        //判断当前商品是否参加秒杀
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        if (seckillGoods != null) {
            if (DateUtil.dateCompare(seckillGoods.getStartTime(), new Date())
                    && DateUtil.dateCompare(new Date(), seckillGoods.getEndTime())) {
                String skuIdStr = MD5.encrypt(userId);
                return Result.ok(skuIdStr);
            }
        }
        return Result.fail().message("生成下单码失败!");
    }


    //  下单控制器：/api/activity/seckill/auth/seckillOrder/{skuId}?skuIdStr=skuIdStr
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, HttpServletRequest request) {
        //获取下单码
        String skuIdStr = request.getParameter("skuIdStr");
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);

        //判断数据
        if (!skuIdStr.equals(MD5.encrypt(userId))){
            return Result.fail().message("校验下单失败");
        }
        //  校验状态位： skuId:1  skuId:0
        String status = (String) CacheHelper.get(skuId.toString());
        if ("0".equals(status)) {
            return Result.fail().message("商品已售罄!");
        }else if (StringUtils.isEmpty(status)){
            return Result.fail().message("非法秒杀!");
        }else {
            UserRecode userRecode = new UserRecode();
            userRecode.setSkuId(skuId);
            userRecode.setUserId(userId);

            //发送到消息队列
            this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,MqConst.EXCHANGE_DIRECT_SECKILL_USER,userRecode);
            return Result.ok();
        }
    }
}
